#!BPY

"""
Name: 'ViBos Model (.vib)...'
Blender: 243
Group: 'Export'
Tooltip: 'Save a ViBos ModelViBos Model  File'
"""

__author__ = "Jon Valdes"
__version__ = "1.0"

__bpydoc__ = """\
 This script is an exporter to OBJ file format.

	Usage:
		First do "Transform->Clear/Apply->Apply Scale/Rotation to ObData" on all objects on the scene
		Then run this script from "File->Export" menu and select a destination file. Only mesh objects will be exported and UVs will not be stored in the file.
	"""

from Blender import Window, Scene, Draw, Mathutils
import Blender 
import bpy

def write_vib(filepath):
	out = file(filepath, 'w')
	out.write("VIBOSMODEL VERSION 100\nTREEMODEL exampleName\n")
	
	sce = Blender.Scene.GetCurrent()
	for ob in sce.objects:
		if ob.getType() == 'Mesh':
			write_vib_mesh(ob,out)
	out.close();

def angle_tween_vectors(vec1, vec2):
	if vec1.length == 0 or vec2.length == 0:
		return 0
	return Mathutils.AngleBetweenVecs(vec1,vec2)

def write_vib_mesh(ob, out):
	mesh = ob.getData(mesh=1)
	mesh.calcNormals()

	out.write('MESH %s BASECOLOR 1.0 1.0 1.0\n' % ob.getName() )

	for vert in mesh.verts:
		out.write( 'P %f %f %f N %f %f %f UV 0.0 0.0 AO 0.5\n' % (vert.co.x+ob.LocX, vert.co.z+ob.LocZ, -(vert.co.y+ob.LocY), vert.no.x, vert.no.z, vert.no.y) )

	for face in mesh.faces:
			write_face(face,out, 1)
		

def write_face(face, out, reverse):
	if angle_tween_vectors(Mathutils.TriangleNormal(face.v[0].co, face.v[1].co,face.v[2].co), face.no) > 90 :
		reverse = 1
	else:
		reverse = 0

	out.write('TRI')
	out.write( ' %i' % (face.v[0].index) )
	if reverse == 0:
		out.write( ' %i' % (face.v[2].index) )
		out.write( ' %i' % (face.v[1].index) )
	else:
		out.write( ' %i' % (face.v[1].index) )
		out.write( ' %i' % (face.v[2].index) )
	
	out.write('\n')
	if len(face.verts) == 4:
		if angle_tween_vectors(Mathutils.TriangleNormal(face.v[0].co, face.v[2].co,face.v[3].co), face.no) > 90 :
			reverse = 1
		else:
			reverse = 0

		out.write('TRI')
		out.write( ' %i' % (face.v[0].index) )
		if reverse == 0:
			out.write( ' %i' % (face.v[3].index) )
			out.write( ' %i' % (face.v[2].index) )
		else:
			out.write( ' %i' % (face.v[2].index) )
			out.write( ' %i' % (face.v[3].index) )

		out.write('\n')

Blender.Window.FileSelector(write_vib, "Export")

